import { reactive, ref } from 'vue';
import { useI18n } from '@/service/helper';
import { checkCaptchaApi, resetPasswordApi } from '../../app-login/api/login';
import { PAGE_LOGIN_URL } from '../../app-login/hooks/constant';
import { sendCaptcha } from '../../app-login/hooks/use-login';
import { resetPasswordValidate, dynamicLoginValidate } from '../../app-login/hooks/use-validate';
import { debounce, Modal } from '@jecloud/utils';
import { useLoginTheme } from '../../app-login/hooks/use-login';
export function usePassword() {
  const validate = ref(false);
  const loading = ref(false);
  const model = reactive({ phone: '', captcha: '', newPassword: '', confirmPassword: '' });
  // 发送验证码
  const onTimerClick = debounce(($timer) => {
    sendCaptcha({ model, $timer }).then((message) => {
      Modal.toast(message, 'success');
    });
  }, 200);
  // 下一步
  const onNextClick = () => {
    loading.value = true;
    dynamicLoginValidate({ model })
      .then(() => checkCaptchaApi(model))
      .then(() => {
        loading.value = false;
        validate.value = true;
      })
      .catch(({ message }) => {
        loading.value = false;
        Modal.toast({ message, status: 'error' });
      });
  };
  // 确认
  const onOkClick = () => {
    loading.value = true;
    resetPasswordValidate({ model })
      .then(() => resetPasswordApi(model))
      .then(() => {
        reLoginToast({ toast: Modal.toast });
      })
      .catch(({ message }) => {
        loading.value = false;
        Modal.toast({ message, status: 'error' });
      });
  };
  return {
    validate,
    loading,
    model,
    onNextClick,
    onOkClick,
    onTimerClick,
    ...useLoginTheme(),
  };
}
/**
 * 重新登录提示
 * @param {*} param0
 */
export function reLoginToast({ toast }) {
  const { t } = useI18n();
  toast({
    message: t('login.message.resetPasswordSuccess', [3]),
    status: 'success',
  });
  setTimeout(() => {
    uni.reLaunch({ url: PAGE_LOGIN_URL });
  }, 3000);
}
